package org.leetcode.easy.leetcode141;

import org.algorithm.List.ListNode;

import java.util.HashSet;
import java.util.List;

public class Solution {
    public boolean hasCycle6(ListNode head) {
        if (head==null || head.next==null){
            return false;
        }

        ListNode fast = head.next;
        ListNode slow = head;

        while (fast != slow) {
            if (fast==null || fast.next==null){
                return false;
            }
            fast = fast.next.next;
            slow = slow.next;
        }

        return true;
    }

    public boolean hasCycle5(ListNode head) {

        HashSet<ListNode> hashSet = new HashSet<>();

        while (head != null) {
            if (hashSet.contains(head)) {
                return true;
            } else {
                hashSet.add(head);
            }
            head = head.next;
        }

        return false;
    }

    public boolean hasCycle3(ListNode head) {

        if (head == null || head.next == null) {
            return false;
        }

        ListNode slow = head;
        ListNode fast = head.next;

        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }

            slow = slow.next;
            fast = fast.next.next;
        }

        return true;
    }

    public boolean hasCycle2(ListNode head) {
        HashSet<ListNode> set = new HashSet<>();

        while (head != null) {
            if (!set.add(head)) {
                return true;
            }

            head = head.next;
        }

        return false;

    }

    public boolean hasCycle(ListNode head) {


        ListNode slow = head;
        ListNode fast = head.next;

        if (slow == null || fast == null) {
            return false;
        }

        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }

            slow = slow.next;

            fast = fast.next.next;
        }

        return true;
    }
}
